﻿using System;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace ClassicPassWd
{
    /// <summary>
    /// ColumnExchange.xaml 的交互逻辑
    /// </summary>
    public partial class ColumnExchange : UserControl
    {
        public ColumnExchange()
        {
            InitializeComponent();
        }

        private void BoxProclaim_OnTextChanged(object sender, TextChangedEventArgs e)
        {
            BoxPassword.Text = "";
            if (BoxProclaim.Text != "")
                GetPassword((int)Slider.Value);
        }

        private void Slider_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            BoxPassword.Text = "";
            if (BoxProclaim.Text != "")
                GetPassword((int)Slider.Value);
        }

        private void GetPassword(int length)
        {
            string str = BoxProclaim.Text.Replace(" ", "");
            Slider.Maximum = BoxProclaim.Text == "" ? 0 : str.Length;
            ArrayList list = SplitLength(str, length);
            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < length; i++)
            {
                for (int j = 0; j < (int)Math.Ceiling((double)str.Length / length); j++)
                {
                    if (list[j].ToString().ToCharArray()[i] == '\0')
                        builder.Append("");
                    builder.Append(list[j].ToString().ToCharArray()[i]);
                }

                builder.Append(" ");

            }

            BoxPassword.Text = builder.ToString();

        }

        public ArrayList SplitLength(string SourceString, int Length)
        {
            //List<string> DestString = new List<string>();
            ArrayList list = new ArrayList();
            for (int i = 0; i < SourceString.Trim().Length; i += Length)
            {
                if ((SourceString.Trim().Length - i) >= Length)
                    list.Add(SourceString.Trim().Substring(i, Length));
                else
                    list.Add(SourceString.Trim().Substring(i, SourceString.Trim().Length - i));
            }

            StringBuilder builder = new StringBuilder(list[list.Count - 1].ToString());
            for (int i = list[list.Count - 1].ToString().Length; i < Length; i++)
            {
                builder.Append('\0');
            }

            list[list.Count - 1] = builder.ToString();
            return list;
        }

        private void BoxProclaim_OnPreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Space)
            {
                e.Handled = false;
                return;
            }
            e.Handled = new Regex("[^A-Za-z]").IsMatch(GetCharFromKey.KeyChars(e.Key).ToString());
        }
    }
}